package com.ruoyi.web.controller.insect.controller;

import java.util.List;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.insect.domain.DiseaseRecord;
import com.ruoyi.insect.service.IDiseaseRecordService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 病虫害识别记录Controller
 */
@RestController
@RequestMapping("/insect/record")
public class DiseaseRecordController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(DiseaseRecordController.class);

    @Autowired
    private IDiseaseRecordService diseaseRecordService;

    /**
     * 查询病虫害识别记录列表
     */
    @PreAuthorize("@ss.hasPermi('insect:record:list')")
    @GetMapping("/list")
    public TableDataInfo list(DiseaseRecord diseaseRecord) {
        startPage();
        List<DiseaseRecord> list = diseaseRecordService.selectDiseaseRecordList(diseaseRecord);

        // 记录图片数据长度用于调试
        for (DiseaseRecord record : list) {
            if (StringUtils.isNotEmpty(record.getResultImage())) {
                logger.info("记录ID: {}, 结果图片数据长度: {}", record.getId(), record.getResultImage().length());
            }
            if (StringUtils.isNotEmpty(record.getOriginalImage())) {
                logger.info("记录ID: {}, 原始图片数据长度: {}", record.getId(), record.getOriginalImage().length());
            }
        }

        return getDataTable(list);
    }

    /**
     * 获取病虫害识别记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('insect:record:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        DiseaseRecord diseaseRecord = diseaseRecordService.selectDiseaseRecordById(id);

        if (diseaseRecord != null) {
            // 记录图片数据信息用于调试
            if (StringUtils.isNotEmpty(diseaseRecord.getResultImage())) {
                logger.info("详情查询 - 记录ID: {}, 结果图片数据长度: {}, 前100字符: {}",
                        id, diseaseRecord.getResultImage().length(),
                        diseaseRecord.getResultImage().substring(0, Math.min(100, diseaseRecord.getResultImage().length())));
            }
        }

        return AjaxResult.success(diseaseRecord);
    }

    /**
     * 新增病虫害识别记录
     */
    @PreAuthorize("@ss.hasPermi('insect:record:add')")
    @Log(title = "病虫害识别记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DiseaseRecord diseaseRecord) {
        try {
            // 验证图片数据
            //if (diseaseRecord.getResultImage() == null || diseaseRecord.getResultImage().trim().isEmpty()) {
             //   return AjaxResult.error("识别结果图片不能为空");
            //}

            // 记录接收到的图片数据信息
            logger.info("接收到的结果图片数据长度: {}", diseaseRecord.getResultImage().length());
            logger.info("接收到的原始图片数据长度: {}",
                    diseaseRecord.getOriginalImage() != null ? diseaseRecord.getOriginalImage().length() : 0);

            // 处理Base64数据
            String resultImage = processBase64Data(diseaseRecord.getResultImage());
            if (resultImage == null) {
                return AjaxResult.error("识别结果图片数据格式不正确");
            }
            diseaseRecord.setResultImage(resultImage);

            // 处理原始图片
            if (StringUtils.isNotEmpty(diseaseRecord.getOriginalImage())) {
                String originalImage = processBase64Data(diseaseRecord.getOriginalImage());
                diseaseRecord.setOriginalImage(originalImage);
            }

            int result = diseaseRecordService.insertDiseaseRecord(diseaseRecord);
            if (result > 0) {
                return AjaxResult.success("保存成功");
            } else {
                return AjaxResult.error("保存失败");
            }
        } catch (Exception e) {
            logger.error("保存病虫害识别记录失败", e);
            return AjaxResult.error("保存失败: " + e.getMessage());
        }
    }

    /**
     * 处理Base64图片数据
     */
    private String processBase64Data(String base64Data) {
        if (StringUtils.isEmpty(base64Data)) {
            return null;
        }

        // 如果已经是纯Base64数据（不包含data URL前缀），直接返回
        if (isPureBase64(base64Data)) {
            logger.info("检测到纯Base64数据，长度: {}", base64Data.length());
            return base64Data;
        }

        // 处理data URL格式
        if (base64Data.startsWith("data:")) {
            // 提取Base64部分
            String[] parts = base64Data.split(",");
            if (parts.length == 2) {
                String base64Part = parts[1];
                logger.info("从data URL提取Base64数据，长度: {}", base64Part.length());
                return base64Part;
            } else {
                logger.error("无效的data URL格式");
                return null;
            }
        }

        logger.error("未知的图片数据格式");
        return null;
    }

    /**
     * 检查是否为纯Base64数据
     */
    private boolean isPureBase64(String data) {
        // 简单的Base64格式检查
        return data != null &&
                !data.startsWith("data:") &&
                data.matches("^[A-Za-z0-9+/]*={0,2}$");
    }

    /**
     * 修改病虫害识别记录
     */
    @PreAuthorize("@ss.hasPermi('insect:record:edit')")
    @Log(title = "病虫害识别记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DiseaseRecord diseaseRecord) {
        return toAjax(diseaseRecordService.updateDiseaseRecord(diseaseRecord));
    }

    /**
     * 删除病虫害识别记录
     */
    @PreAuthorize("@ss.hasPermi('insect:record:remove')")
    @Log(title = "病虫害识别记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(diseaseRecordService.deleteDiseaseRecordByIds(ids));
    }

    /**
     * 导出病虫害识别记录列表
     */
    @PreAuthorize("@ss.hasPermi('insect:record:export')")
    @Log(title = "病虫害识别记录", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(DiseaseRecord diseaseRecord) {
        List<DiseaseRecord> list = diseaseRecordService.selectDiseaseRecordList(diseaseRecord);
        ExcelUtil<DiseaseRecord> util = new ExcelUtil<DiseaseRecord>(DiseaseRecord.class);
        return util.exportExcel(list, "病虫害识别记录数据");
    }
}
